package com.teamin.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.core.util.StringUtils;
import com.teamin.entity.WXEntiti;
import com.teamin.entity.WxUserEntity;
import com.teamin.service.UserService;
import com.teamin.service.impl.wx.WeChatMPTokenManager;
import com.teamin.web.exception.GlobalErrorInfoException;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

@RestController
@Api(tags = "微信服务")
public class WXController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	public final String EVENT_SUBSCRIBE="subscribe" ;//关注公众号
	public final String EVENT_UNSUBSCRIBE="unsubscribe" ;//取消关注公众号
	@Autowired
	private UserService userService;
	/**
	 * 验证微信服务器
	 */
	@RequestMapping(value = "/v1/wxserver/action/event", method = RequestMethod.GET)
	public void wxServer(HttpServletRequest request, HttpServletResponse response)
			throws GlobalErrorInfoException {
		Map<String, String[]> re = request.getParameterMap();
		Iterator<Map.Entry<String, String[]>> iter = re.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, String[]> next = iter.next();
		}

		if (request.getParameterMap().containsKey("echostr") && !StringUtils.isNullOrEmpty(request.getParameter("echostr"))) {
			String echostr = request.getParameter("echostr");
			flushDataByStringToResponse(response, echostr);
		}
	}

	/**
	 * 接收微信服务器发送过来的消息 由外网的WX服务器来处理关注
	 */
	@RequestMapping(value = "/v1/wxserver/action/event", method = RequestMethod.POST)
	public void wxServerPost(HttpServletRequest request, HttpServletResponse response)
			throws GlobalErrorInfoException, IOException {
		WXEntiti data = getRequestData(request, WXEntiti.class);
		logger.info("post = "+data.toString());
		if(EVENT_SUBSCRIBE.equals(data.getEvent())) {//关注公信公众号事件
			JSONObject wxUserInfo = WeChatMPTokenManager.getInstance().getUserByOpenId(data.getFromUserName());
			logger.info(wxUserInfo.toString());
			WxUserEntity we = new WxUserEntity() ;
					we.setUnionId(wxUserInfo.getString("unionid"));
			we.setAvatarUrl(wxUserInfo.getString("headimgurl"));
			we.setLanguage(wxUserInfo.getString("language"));
			we.setMpOpenId(wxUserInfo.getString("openid"));
			we.setNickName(wxUserInfo.getString("nickname"));
			userService.saveOrUpdateWxUser(we) ;
		}else if( EVENT_UNSUBSCRIBE.equals(data.getEvent())) {//取消关注公众号事件
			userService.cancleMPAttention(data.getFromUserName()) ;
		}

	}
}
